package com.ai.notices.utils.mongo;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.annotation.PostConstruct;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.mongodb.gridfs.GridFSDBFile;

import net.sf.json.JSONObject;

/**
 * 基于MongoDB的文件服务实现类
 * @author microzhu
 */
@Service
public class MongoFileManagerSVCImpl implements ConfigurationWatcher, FileManagerSVC{
	
	private static final Logger log = Logger.getLogger(MongoFileManagerSVCImpl.class);
		
	private String confPath = "/com/ai/paas/mongodb/conf";
    private static final String USERNAME_KEY = "username";
    private static final String PASSWORD_KEY = "password";
    private static final String SERVER_KEY="fileServer";
    private static final String DBNAME_KEY="fileRepo";
    private String configurationFile="/PaasConfigurationFile.properties";
    private String fileServer = null;
	private String fileRepo = null;
	private String userName = null;
	private String password = null;
    private MongoDBClient mongo = null;
    private  Properties props = new Properties();
    
	public MongoFileManagerSVCImpl() {
		//init();
	}
	@PostConstruct
	public void init() {
		try {
			this.props.load(this.getClass().getResourceAsStream(configurationFile));
        	String path = (String)this.props.get(confPath);
        	process(path);
			
		} catch (Exception e) {
			log.error("mongodb连接初始化错误。",e);
		}
	}
	
	public void process(String conf) {
		// TODO Auto-generated method stub

        if(log.isInfoEnabled()) {
            log.info("new log configuration is received: " + conf);
        }
        JSONObject json = JSONObject.fromObject(conf);
        boolean changed = false;

        if(json.containsKey(SERVER_KEY) && !json.getString(SERVER_KEY).equals(fileServer)) {
            changed = true;
            fileServer = json.getString(SERVER_KEY);
        }
        if(json.containsKey(DBNAME_KEY) && !json.getString(DBNAME_KEY).equals(fileRepo)) {
            changed = true;
            fileRepo = json.getString(DBNAME_KEY);
        }
        if(json.containsKey(USERNAME_KEY) && !json.getString(USERNAME_KEY).equals(userName)) {
            changed = true;
            userName = json.getString(USERNAME_KEY);
        }
        if(json.containsKey(PASSWORD_KEY) && !json.getString(PASSWORD_KEY).equals(password)) {
            changed = true;
            password = json.getString(PASSWORD_KEY);
        }

        if(changed) {
            if(fileServer != null) {
                mongo = new MongoDBClient(fileServer,fileRepo, userName, password);
                if(log.isInfoEnabled()) {
                    log.info("log server address is changed to " + fileServer);
                }
            }
        }
    
	}
	public String saveFile(String fileName, String fileType) {
		return mongo.saveFile(fileRepo, fileName, fileType);
	}
	public String saveFile(byte[] byteFile, String fileName, String fileType) {
		return mongo.saveFile(fileRepo, byteFile,fileName,fileType);
	}

	@Override
	public String saveFile(InputStream inputStream, String fileName, String fileType) {
		return mongo.saveFile(fileRepo,inputStream,fileName,fileType);
	}

	public byte[] readFile(String fileId) {
		return mongo.readFile(fileRepo, fileId);
	}
	public byte[] readFileByName(String fileName) {
		return mongo.readFileByName(fileRepo, fileName);
	}
	public void readFile(String fileId, String localFileName) {
		mongo.readFile(fileRepo, fileId, localFileName);
	}
	public void readFileByName(String fileName, String localFileName) {
		mongo.readFileByName(fileRepo, fileName, localFileName);
	}
	public void deleteFile(String fileId) {
		mongo.deleteFile(fileRepo, fileId);
	}
	
	public void deleteFileByName(String fileName) {
		mongo.deleteFileByName(fileRepo, fileName);
	}
	
	public Date readFileAndUpdateTime( String fileId, String localFileName) {

	    return mongo.readFileAndUpdateTime(fileRepo, fileId, localFileName);
    }

    public Date readUpdateTime(String fileId) {
        
        return mongo.readUpdateTime(fileRepo, fileId);
    }
    /**
     * 带条件查询
     *
     * @param condition
     * @param condition
     */
    public List<GridFSDBFile> queryWithCondition(Map<String, String> condition) {
        
        return mongo.queryWithCondition(fileRepo, condition);
    }
    
    @Override
    public String getFileName(String fileId) {
        return mongo.getFileName(fileRepo, fileId);
    }

	@Override
	public String getFileType(String fileId) {
		return mongo.getContentType(fileRepo,fileId);
	}

	@Override
	public void readFile(String fileId, OutputStream ops) {

		mongo.readFile(fileRepo,fileId,ops);
	}

	@Override
	public InputStream readFile2ips(String fileId) {
		return mongo.readFile2ips(fileRepo,fileId);
	}

	public String updateFile(byte[] byteFile, String fileId, String fileName, String fileType) throws Exception {

        return mongo.updateFile(fileRepo, byteFile, fileId, fileName, fileType);
    }
	
    public String updatePropertyOfFile(String fileId, String fileName,
            String fileType) throws Exception{
        
        return mongo.updatePropertyOfFile(fileRepo, fileId, fileName, fileType);
    }
	
	

	public static void main(String[] args) throws Exception{
		//ApplicationContext ctx = new ClassPathXmlApplicationContext(new String[] { "clientSenderContext.xml" });
		
//		FileManager manager = (FileManager)PaasContextHolder.getContext().getBean("secureFileRepo");
//		System.out.println(manager.saveFile("/Users/ZhangJunyong/Workspace/01_工作文档/01_支付平台/04_支付通道/一般支付和UPOP无卡支付/MerPrK_808080110594439_20141105145807.key", "key"));
//		FileManager manager = (FileManager)PaasContextHolder.getContext().getBean("secureFileRepo");
//		System.out.println(manager.saveFile("/Users/ZhangJunyong/Workspace/01_工作文档/01_支付平台/10_接入文档/测试平台密钥/public.cer", "cer"));
//		manager.readFile("53c398ca30045257c78b6f93", "/Volumes/HD/Downloads/53c398ca30045257c78b6f93");
		//FileManagerSVC manager = (FileManagerSVC)PaasContextHolder.getContext().getBean("fileManager");
//		System.out.println(manager.saveFile("/Users/ZhangJunyong/ec_workspace/service/config/distributedRule-local.xml", "xml"));
		//System.out.println(manager.saveFile("/Users/ZhangJunyong/Workspace/01_工作文档/01_支付平台/03_机密文件/4111.png", "png"));
//		FileManager manager = (FileManager)PaasContextHolder.getContext().getBean("secureFileRepo");
//		System.out.println(manager.saveFile("/Users/ZhangJunyong/Downloads/terminalMacKey", "key"));
//		System.out.println(manager.saveFile("/Volumes/HD/Downloads/53a7e874392ad15c6df3b835", "key"));
//		manager.readFile("53a7e874392ad15c6df3b835", "/Volumes/HD/Downloads/53a7e874392ad15c6df3b835");
//		File file = new File("/Volumes/HD/Downloads/bbb1.jpg");
		//ByteArrayInputStream bais = new ByteArrayInputStream(manager.readFile("53a39cf515376325c4709694"));
//		FileOutputStream fos = new FileOutputStream(file);
//		fos.write(manager.readFile("53a39cf515376325c4709694"));
		//manager.deleteFile("536e28261a884ead50efe832");
//		manager.deleteFileByName("mongo-java-driver-2.12.0-javadoc.jar");
//		FileManager manager = (FileManager)PaasContextHolder.getContext().getBean("ruleRepo");
//		System.out.println(manager.saveFile("/Users/ZhangJunyong/ec_workspace/service/rule/aipayRule.drl", "drl"));
//		FileManager manager = (FileManager)PaasContextHolder.getContext().getBean("secureFileRepo");
//		System.out.println(manager.saveFile("/Users/ZhangJunyong/Workspace/01_工作文档/01_支付平台/10_接入文档/测试平台密钥/hmall_public_test.cer", "cer"));
//		FileManager manager = (FileManager)PaasContextHolder.getContext().getBean("fileManager");
//		System.out.println(manager.saveFile("/Users/ZhangJunyong/Workspace/01_工作文档/01_支付平台/10_接入文档/平台接口协议/public_key.cer", "cer"));
//		FileManager manager = (FileManager)PaasContextHolder.getContext().getBean("secureFileRepo");
//		System.out.println(manager.saveFile("/Users/ZhangJunyong/Workspace/01_工作文档/01_支付平台/10_接入文档/平台接口协议/test_public_key.cer", "cer"));
//		FileManager manager = (FileManager)PaasContextHolder.getContext().getBean("fileManager");
//		System.out.println(manager.saveFile("/Users/ZhangJunyong/Workspace/01_工作文档/01_支付平台/10_接入文档/测试平台密钥/sign.jpg", "jpg"));
//		FileManager manager = (FileManager)PaasContextHolder.getContext().getBean("fileManager");
//		System.out.println(manager.saveFile("/Users/ZhangJunyong/ec_workspace/distributedDbPrj_multiTenant/config/distributedRule.xml", "xml"));
		FileManagerSVC file = new MongoFileManagerSVCImpl(); 
		//582ad6851e0e0f6631ed2a21.jpg --5943cd8b976e6e096fbe5101
		//System.out.println(file.saveFile("/Users/microzhu/Downloads/582ad6851e0e0f6631ed2a21.jpg", "jpg"));
		System.out.println(file.getFileName("5943cd8b976e6e096fbe5101"));
	}
}
